package com.opages.mvc.adapter.consul.discovery;

import com.ecwid.consul.v1.health.model.HealthService;
import com.netflix.loadbalancer.Server;
import com.opages.mvc.adapter.common.client.ServiceInstance;
import org.springframework.util.StringUtils;

import static com.opages.mvc.adapter.consul.utils.ConsulServiceUtils.findHostByHealth;

import java.util.*;

/**
 * @author daizhong.liu
 * @create 2020-06-15 10:57
 **/
public class ConsulServiceInstance extends Server implements ServiceInstance {

    private final HealthService healthService;

    public ConsulServiceInstance(final HealthService healthService) {
        super(findHostByHealth(healthService), healthService.getService().getPort());
        this.healthService = healthService;
    }

    @Override
    public String getServiceId() {
        return this.healthService.getService().getId();
    }

    @Override
    public boolean isSecure() {
        try {
            Iterator<String> iterator = healthService.getService().getTags().iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                String[] tag = next.split("=");
                if ("secure".equals(tag[0])) {
                    return Boolean.parseBoolean(tag[1]);
                }
            }
        }catch (Exception e){}
        return false;
    }

    @Override
    public String getScheme() {
        if(isSecure()) {
            return "https";
        }else {
            return "http";
        }

    }

    @Override
    public Map<String, String> getMetadata() {
        LinkedHashMap<String, String> metadata = new LinkedHashMap<>();
        List<String> tags = healthService.getService().getTags();
        if (tags != null) {
            for (String tag : tags) {
                String[] parts = StringUtils.delimitedListToStringArray(tag, "=");
                switch (parts.length) {
                    case 0:
                        break;
                    case 1:
                        metadata.put(parts[0], parts[0]);
                        break;
                    case 2:
                        metadata.put(parts[0], parts[1]);
                        break;
                    default:
                        String[] end = Arrays.copyOfRange(parts, 1, parts.length);
                        metadata.put(parts[0], StringUtils.arrayToDelimitedString(end, "="));
                        break;
                }
            }
        }
        return metadata;
    }
}
